package com.example.sunmiv1.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;


import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;


import androidx.recyclerview.widget.RecyclerView;

import com.example.sunmiv1.R;
import com.example.sunmiv1.adapter.DepositGoodsAdapter;

import com.example.sunmiv1.base.BaseChooseActivity;
import com.example.sunmiv1.entity.ClassificationBean;
import com.example.sunmiv1.entity.DepositGoodsInfo;
import com.example.sunmiv1.entity.ReportLossGoodBean;
import com.example.sunmiv1.utils.LogUtil;
import com.example.sunmiv1.utils.Tools;
import com.example.sunmiv1.utils.net.Common;
import com.example.sunmiv1.utils.net.GsonUtils;
import com.example.sunmiv1.utils.net.HttpUtils;
import com.example.sunmiv1.utils.net.TextCallBack;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

//
// 採購管理.採購單.新增採購單.選擇頁面
public class DepositGoodsActivity extends BaseChooseActivity {

    @BindView(R.id.title_back)
    ImageView titleBack;
    @BindView(R.id.title_title)
    TextView titleTitle;
    @BindView(R.id.view_bg_top)
    View viewBgTop;
    @BindView(R.id.tv_pick_sort)
    TextView tvPickSort;
    @BindView(R.id.ed_num_search)
    EditText edNumSearch;
    @BindView(R.id.iv_search_code)
    ImageView ivSearchCode;
    @BindView(R.id.iv_search)
    ImageView ivSearch;
    @BindView(R.id.view_bg_footer)
    View viewBgFooter;
    @BindView(R.id.btn_checkall)
    Button btnCheckall;
    @BindView(R.id.btn_add_to_list)
    Button btnAddToList;
    @BindView(R.id.rv_goods_choose)
    RecyclerView rvGoodsChoose;
    @BindView(R.id.btn_ok)
    Button btnOk;
    @BindView(R.id.btn_checkall_not)
    Button btnCheckallNot;
    @BindView(R.id.btn_to_top)
    ImageView btnToTop;
    @BindView(R.id.progress_bar)
    ProgressBar progressBar;


    private DepositGoodsInfo depositGoodsInfo;
    private ArrayList<DepositGoodsInfo.DataBean.ListBean> choiceList;//已經選擇的商品集合
    private List<DepositGoodsInfo.DataBean.ListBean> dataList;//所有的商品集合
    private DepositGoodsAdapter adapter;


    private int type;//1 AddDepositActivity,2 門店PurchaseOrderAddActivity,3 商戶PurchaseOrderAddActivity

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    progressBar.setVisibility(View.GONE);
                    setAdapter();
                    break;
                case 2:
                    setAdapter();
                    break;
                case 3:
                    break;
            }
        }
    };

    @OnClick({R.id.title_back, R.id.btn_to_top, R.id.title_title, R.id.tv_pick_sort, R.id.iv_search_code, R.id.iv_search, R.id.btn_checkall, R.id.btn_checkall_not, R.id.btn_add_to_list, R.id.btn_ok})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                putExtra(this, PurchaseOrderAddActivity.class, choiceList, "");
                break;
            case R.id.iv_search_code:  // 調起掃碼
                startQrCode();
                break;
            case R.id.iv_search:
                LogUtil.i("searchText:" + edNumSearch.getText().toString().trim());
                getListInfo(1);
                break;
            case R.id.btn_checkall:  // 全選操作
                btnCheckall.setVisibility(View.GONE);
                btnCheckallNot.setVisibility(View.VISIBLE);
                adapter.checkAll();
                break;
            case R.id.btn_checkall_not: // 全不選操作
                adapter.checkAllNot();
                btnCheckallNot.setVisibility(View.GONE);
                btnCheckall.setVisibility(View.VISIBLE);
                break;
            case R.id.btn_add_to_list:  //添加到上頁列表中
                addToListAndRemove();
                break;
            case R.id.btn_ok:  //添加到上頁列表並返回
                addToList();
                putExtra(this, PurchaseOrderAddActivity.class, choiceList, "");
                break;
            case R.id.tv_pick_sort:  //分類篩選
                if (classificationBean != null && classificationBean.getStatus() == 1 && classificationBean.getGoodscate().size() > 0) {
//                    showPickerView(options1Items,options2Items,options3Items,classificationBean);
                    showPickerView();
                } else {
                    Toast.makeText(this, "無法獲取分類列表", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_to_top:
                rvGoodsChoose.smoothScrollToPosition(0);
                break;
        }
    }

    @Override
    protected void initChoiceList() {
        btnAddToList.setText(R.string.addDepositGoodsList);
        dataList = new ArrayList<>();  // 顯示信息列表
        choiceList = new ArrayList<>();// 已選擇列表
    }

    @Override
    protected void getListInfo(int page) {
        searchGood(page);
    }

    /* 添加到回傳列表中，並且移除當前頁面*/
    protected void addToListAndRemove() {
        for (int i = dataList.size() - 1; i >= 0; i--) {
            if (dataList.get(i).isChecked()) {
                notInIdArr.add(dataList.get(i).getId());
                adapter.notifyItemRemoved(i);
                choiceList.add(dataList.remove(i));
            }
        }
    }

    /* 直接添加到回傳列表*/
    protected void addToList() {
        for (int i = dataList.size() - 1; i >= 0; i--) {
            if (dataList.get(i).isChecked()) {
                choiceList.add(dataList.remove(i));
            }
        }
    }

    private Intent intent;

    @Override
    protected void setAdapter() {
        if (adapter == null) {
//            dataList = new ArrayList<>();  // 顯示信息列表
            adapter = new DepositGoodsAdapter(this, dataList, type);
            rvGoodsChoose.setAdapter(adapter);
        } else {
            adapter.notifyDataSetChanged();
        }
        adapter.setChoose(new DepositGoodsAdapter.Choose() {
            @Override
            public void choose(int index) {
                intent = new Intent(context, StringCodeOperationActivity.class);
                if (type == 1) {
                    intent.putExtra("operation", 8);
                } else {
                    intent.putExtra("operation", 9);
                }
                intent.putExtra("good", dataList.get(index));
                ArrayList<String> serialList = new ArrayList<>();
                for (DepositGoodsInfo.DataBean.ListBean bean : choiceList) {
                    if ("1".equals(bean.getSerial_number_state())) {
                        for (DepositGoodsInfo.DataBean.ListBean.SerialBean b : bean.getSerialList()) {
                            serialList.add(b.getMain_serial_number());
                            if (!TextUtils.isEmpty(b.getAuxiliary_serial_number_one())) {
                                serialList.add(b.getAuxiliary_serial_number_one());
                            }
                            if (!TextUtils.isEmpty(b.getAuxiliary_serial_number_two())) {
                                serialList.add(b.getAuxiliary_serial_number_two());
                            }
                        }
                    }
                }
                intent.putStringArrayListExtra("list",serialList);
                startActivityForResult(intent, 200);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 200:
                    DepositGoodsInfo.DataBean.ListBean bean = (DepositGoodsInfo.DataBean.ListBean) data.getSerializableExtra("bean");
                    int index = 0;
                    for (int t = 0; t < dataList.size(); t++) {
                        if (bean.getGoods_id().equals(dataList.get(t).getGoods_id())) {
                            if ("2".equals(bean.getAttribute_state())) {
                                if (bean.getSku_id().equals(dataList.get(t).getSku_id())) {
                                    index = t;
                                    break;
                                }
                            } else {
                                index = t;
                                break;
                            }
                        }
                    }
                    dataList.set(index, bean);
                    setAdapter();
                    break;
            }
        }

    }

    @Override
    protected void initListener() {
        adapter.setCBListener((isChecked, position) -> {
            dataList.get(position).setChecked(isChecked);
            if (choiceList.size() == dataList.size()) {
                btnCheckall.setVisibility(View.GONE);
                btnCheckallNot.setVisibility(View.VISIBLE);
//                LogUtil.i(R.string.purRefundAdding_check_all);
            }
        });
    }

    /* 監聽手機系統返回鍵*/
    @Override
    public void onBackPressed() {
        putExtra(this, PurchaseOrderAddActivity.class, choiceList, "");
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
    }


    /*搜索商品*/
    private void searchGood(int page) {
//        LogUtil.i("DepositGoodsActivity.notInIdArr:"+notInIdArr.size());
        loadingDialog.show();
        JSONObject jsonObject = new JSONObject();
        String url;
        if ("1".equals(userType)) {//商戶
            url = Common.MER_PUR_GOODS;
        } else {//門店
            url = Common.STORE_PUR_GOODS;
        }
        try {
            jsonObject.put("page", page);
            jsonObject.put("limit", limit);
            jsonObject.put("person1", category[0]);//一級分類id
            jsonObject.put("person2", category[1]);//二級分類id
            jsonObject.put("person3", category[2]);//三級分類id
            jsonObject.put("exists_id_arr", toNotInIds(notInIdArr));
            jsonObject.put("search_info", edNumSearch.getText().toString().trim());
            jsonObject = Tools.createParameterCode(jsonObject);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        HttpUtils.post(this, url, jsonObject, new TextCallBack() {
            @Override
            protected void onSuccess(String text) {
                depositGoodsInfo = new Gson().fromJson(text, DepositGoodsInfo.class);
//                depositGoodsInfo = GsonUtils.JsonToBean(text, DepositGoodsInfo.class);
                loadingDialog.dismiss();
                if (depositGoodsInfo.getStatus() == 1) {
                    if (page == 1) {
                        dataList.clear();
                    }
                    dataList.addAll(depositGoodsInfo.getData().getList());
                    handler.sendEmptyMessage(1);
                    if (dataList.isEmpty()) {
                        Toast.makeText(DepositGoodsActivity.this, "未找到對應貨物", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(DepositGoodsActivity.this, depositGoodsInfo.getMsg(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            protected void onFailure(ResponseException e) {
                loadingDialog.dismiss();
            }
        });

    }

    private void searchOtherGood() {
        JSONObject jsonObject = new JSONObject();
        String url;
        if ("1".equals(userType)) {
            url = Common.MER_PUR_GOODS;
        } else {
            url = Common.STORE_PUR_GOODS;
        }
        try {
            jsonObject.put("page", "");
            jsonObject.put("limit", "");
            jsonObject.put("person1", category[0]);//一級分類id
            jsonObject.put("person2", category[1]);//二級分類id
            jsonObject.put("person3", category[2]);//三級分類id
            jsonObject.put("notInIds", toNotInIds(notInIdArr));
            jsonObject.put("searchText", edNumSearch.getText().toString().trim());
            jsonObject.put("user_type", aCache.getAsString("userType"));
            if ("1".equals(aCache.getAsString("userType")) || "2".equals(aCache.getAsString("userType"))) {
                jsonObject.put("operator_id", aCache.getAsString("operator_id"));
            } else {
                jsonObject.put("operator_id", aCache.getAsString("uid"));
            }
            jsonObject.put("storeid", aCache.getAsString("storeid"));
            jsonObject.put("merchantid", aCache.getAsString("merchantid"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
        HttpUtils.post(this, url, jsonObject, new TextCallBack() {
            @Override
            protected void onSuccess(String text) {
                depositGoodsInfo = GsonUtils.JsonToBean(text, DepositGoodsInfo.class);
                loadingDialog.dismiss();
                if (depositGoodsInfo.getStatus() == 1) {
                    dataList.addAll(depositGoodsInfo.getData().getList().subList(4, depositGoodsInfo.getData().getList().size()));
                    handler.sendEmptyMessage(2);
                } else {
                    Toast.makeText(DepositGoodsActivity.this, depositGoodsInfo.getMsg(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            protected void onFailure(ResponseException e) {
                loadingDialog.dismiss();
            }
        });
    }

    @Override
    public void getInfo(String tvShowText) {
        tvPickSort.setText(tvShowText);
        getListInfo(1);
    }


}
